﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JzSport.Model
{
    public class BaseDataRepository
    {
        private JzSportDbContext _dbContext;

        public BaseDataRepository(JzSportDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public void CreateSummary(BaseDataSummary summary)
        {
            _dbContext.Set<BaseDataSummary>().Add(summary);
        }

        public void UpdateSummary(BaseDataSummary summary)
        {
            _dbContext.Entry<BaseDataSummary>(summary).State = System.Data.EntityState.Modified;
        }

        public void CreateItem(BaseDataItem item)
        {
            _dbContext.Set<BaseDataItem>().Add(item);
        }

        public BaseDataSummary GetLatestSummary(string summaryCode)
        {
            return _dbContext.Set<BaseDataSummary>().Where(p => p.IsEnable == true && p.Code == summaryCode).SingleOrDefault();
        }

        public List<BaseDataSummary> GetLatestSummaryList()
        {
            return _dbContext.Set<BaseDataSummary>().Where(p => p.IsEnable == true).ToList();
        }

        public List<BaseDataItem> GetItems(Guid summaryId)
        {
            return _dbContext.Set<BaseDataItem>().Where(p => p.SummaryId == summaryId)
                .OrderBy(p=>p.Code).ToList();
        }

        public BaseDataItem GetItem(string summaryCode, string itemCode)
        {
            return _dbContext.Set<BaseDataItem>().Where(p => p.Code == itemCode)
                .Join(_dbContext.Set<BaseDataSummary>().Where(p => p.Code == summaryCode && p.IsEnable == true),
                l => l.SummaryId,
                r => r.Id,
                (l, r) => l).SingleOrDefault();
        }
    }
}
